package com.wanjl.service;

import com.wanjl.entity.User;
import com.wanjl.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

/**
 * @author sjqn
 * @date 2023/8/27
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * value = "userCache" 缓存的名称，每个缓存下面可以有多个key
     * key="#user.id" 根据key的值来获取缓存数据，如果key的值是动态的，那么key的值就是#user.id，#user就是参数，#user.id就是参数的属性
     * #user 指的是方法形参的名称，id指的是user的id属性
     * @param user
     * @return
     */
    @CachePut(value = "userCache",key="#user.id")
    public User insert(User user){
        userMapper.insert(user);
        return user;
    }

    @CacheEvict(cacheNames = "userCache",key="#id")//删除某个key对应的缓存数据
    public void deleteById(Long id){
        userMapper.deleteById(id);
    }

    @CacheEvict(cacheNames = "userCache",allEntries = true)//删除userCache下所有的缓存数据
    public void deleteAll(){
        userMapper.deleteAll();
    }

    //@Cacheable(cacheNames = "userCache",key="#id")
    @Caching(
            cacheable = { //查询缓存
                    @Cacheable(value = "userCache",key = "#id")
            },
            put = {//更新缓存
                    @CachePut(value = "userCache",key = "#result.name"),
                    @CachePut(value = "userCache",key = "#result.age")
            }
    )
    public User getById(Long id){
        User user = userMapper.getById(id);
        if(user == null){
            throw new RuntimeException("用户不存在");
        }
        return user;
    }



}
